﻿using System;
using System.Windows.Forms;

namespace MortgageCalc
{
    public partial class Form1 : Form
    {
        private Mortgage CalcMortgage = null;
        public Form1()
        {
            InitializeComponent();
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            CalcMortgage = new Mortgage();
            int nPeriod = 0;
            double nInterest = 0;
            double nLoan = 0;
            double nDown = 0;
            double.TryParse(txtInterest.Text, out nInterest);
            double.TryParse(txtLoan.Text, out nLoan);
            double nMonthlyPrincipal = 0;
            double.TryParse(txtDown.Text, out nDown);
            int.TryParse(txtPeriod.Text, out nPeriod);
            nPeriod = nPeriod * 12;
            if (cmbDown.SelectedIndex==0)
            {
                nDown = nLoan * nDown / 100;               
            }
            nLoan = nLoan - nDown;

            CalcMortgage.AnualInterestPerc = nInterest;
            CalcMortgage.Loan = nLoan;
            CalcMortgage.Term = nPeriod;

            for (int i = 0; i < nPeriod; i++)
            {
                double nInd = 0;
                nInd = Math.Pow((1 + CalcMortgage.MonthlyInterest), i);
                nMonthlyPrincipal = nInd * (CalcMortgage.MonthlyPayment() - nLoan * CalcMortgage.MonthlyInterest);
                CalcMortgage.AddAmortization(nMonthlyPrincipal);
            }

            txtMonthly.Text = Math.Round(CalcMortgage.MonthlyPayment(),2).ToString();
            dgvAmortization.DataSource = CalcMortgage.Amortization;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            cmbLoan.SelectedIndex = 0;
            cmbDown.SelectedIndex = 0;
        }
    }
}
